package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/5 22:31
 * @注释
 */
public class FanoutConsumer {
    private static final String EXCHANGE_NAME = "fanout_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("111.229.199.44");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        //创建两个通道
        Channel channel1=connection.createChannel();
        Channel channel2= connection.createChannel();
        //声明交换机
        channel1.exchangeDeclare(EXCHANGE_NAME, "fanout");
        //创建队列1
        String queueName1 = "queue1";
        channel1.queueDeclare(queueName1, true, false, false, null);
        //创建队列
        String queueName2 = "queue2";
        channel2.exchangeDeclare(EXCHANGE_NAME, "fanout");
        channel2.queueDeclare(queueName2, true, false, false, null);
        channel1.queueBind(queueName1, EXCHANGE_NAME, "");
        channel2.queueBind(queueName2, EXCHANGE_NAME, "");
        System.out.println(" [*] Waiting for message");
        DeliverCallback deliverCallback1=(consumerTag, delivery) ->{
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [a] Received '" + message + "'");
        };
        DeliverCallback deliverCallback2=(consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [b] Received '" + message + "'");
        };
        //开始消费消息队列1
        channel1.basicConsume(queueName1,true,deliverCallback1,consumerTag -> { });
        channel2.basicConsume(queueName2,true,deliverCallback2,consumerTag -> { });
    }

}
